package com.gs.pdf.to.word.pdf;

import java.awt.geom.Rectangle2D;
import java.util.ArrayList;
import java.util.List;
import java.util.Set;
import java.util.TreeSet;

public class TableDetector {

    public static class TableCell {
        public final String content;
        public final int row, col;
        public TableCell(String content, int row, int col) {
            this.content = content;
            this.row = row;
            this.col = col;
        }
    }

    public static List<TableCell> detectTable(List<AdvancedPDFExtractor.ContentItem> items) {
        List<TableCell> cells = new ArrayList<>();

        List<Rectangle2D> rects = new ArrayList<>();
        for (AdvancedPDFExtractor.ContentItem item : items) {
            if (item.isRect()) {
                rects.add(item.rect);
            }
        }

        if (rects.size() < 4) return cells;

        for (AdvancedPDFExtractor.ContentItem item : items) {
            if (item.isText()) {
                for (Rectangle2D rect : rects) {
                    if (rect.contains(item.text.x, item.text.y)) {
                        int row = estimateRow(item.text.y, rects);
                        int col = estimateCol(item.text.x, rects);
                        cells.add(new TableCell(item.text.text, row, col));
                        break;
                    }
                }
            }
        }

        return cells;
    }

    private static int estimateRow(float y, List<Rectangle2D> rects) {
        Set<Float> rows = new TreeSet<>();
        for (Rectangle2D r : rects) rows.add((float)r.getY());
        Float[] sorted = rows.toArray(new Float[0]);
        for (int i = 0; i < sorted.length; i++) {
            if (y >= sorted[i] && y <= sorted[i] + 20) return i;
        }
        return 0;
    }

    private static int estimateCol(float x, List<Rectangle2D> rects) {
        Set<Float> cols = new TreeSet<>();
        for (Rectangle2D r : rects) cols.add((float)r.getX());
        Float[] sorted = cols.toArray(new Float[0]);
        for (int i = 0; i < sorted.length; i++) {
            if (x >= sorted[i] && x <= sorted[i] + 50) return i;
        }
        return 0;
    }
}